/**
 * 32. 最长有效括号
 * https://leetcode-cn.com/problems/longest-valid-parentheses/
 */

const parenthesesLeft = 40;
const parenthesesRight = 41;

/**
 * @param {string} s
 * @return {number}
 */
function longestValidParentheses(s) {
  const { length } = s;
  if (!length) return 0;
  const stackValue = new Array(length);
  const stackIndex = new Array(length);
  stackValue[0] = s.charCodeAt(0);
  stackIndex[0] = 0;
  let top = 0;
  for (let i = 1; i < length; i += 1) {
    const code = s.charCodeAt(i);
    if (code === parenthesesRight && stackValue[top] === parenthesesLeft) {
      top -= 1;
    } else {
      top += 1;
      stackValue[top] = code;
      stackIndex[top] = i;
    }
  }
  if (top < 0) {
    return length;
  }
  let max = stackIndex[0];
  for (let i = 1; i <= top; i += 1) {
    const count = stackIndex[i] - stackIndex[i - 1] - 1;
    if (count > max) {
      max = count;
    }
  }
  const topValue = stackIndex[top];
  if (topValue < length - 1) {
    const count = length - topValue - 1;
    if (count > max) {
      max = count;
    }
  }
  return max;
}

console.log(longestValidParentheses('(()') === 2);
console.log(longestValidParentheses(')()())') === 4);
console.log(longestValidParentheses('') === 0);
console.log(longestValidParentheses('()(()') === 2);
console.log(longestValidParentheses('()') === 2);
